import { defineStore } from 'pinia'
import { login as loginApi, logout as logoutApi, getUserInfo } from '@/api/auth'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: JSON.parse(localStorage.getItem('user') || 'null')
  }),

  getters: {
    isAuthenticated: (state) => !!state.token,
    username: (state) => state.user?.username || ''
  },

  actions: {
    /**
     * 登录
     */
    async login(credentials) {
      try {
        console.log('🔐 尝试登录...')
        const res = await loginApi(credentials)
        
        this.token = res.data.token
        this.user = res.data.user
        
        // 保存到localStorage
        localStorage.setItem('token', this.token)
        localStorage.setItem('user', JSON.stringify(this.user))
        
        console.log('✅ 登录成功:', this.user.username)
        ElMessage.success(`欢迎回来，${this.user.username}！`)
        
        return true
      } catch (error) {
        console.error('❌ 登录失败:', error)
        return false
      }
    },

    /**
     * 登出
     */
    async logout() {
      try {
        console.log('👋 用户登出')
        await logoutApi()
      } catch (error) {
        console.error('登出请求失败:', error)
      } finally {
        // 清除本地数据
        this.token = ''
        this.user = null
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        
        ElMessage.success('已退出登录')
      }
    },

    /**
     * 检查认证状态
     */
    async checkAuth() {
      if (!this.token) {
        return false
      }

      try {
        console.log('🔍 检查登录状态...')
        const res = await getUserInfo()
        this.user = res.data
        localStorage.setItem('user', JSON.stringify(this.user))
        console.log('✅ 登录状态有效')
        return true
      } catch (error) {
        console.warn('⚠️  登录状态已失效')
        this.token = ''
        this.user = null
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        return false
      }
    }
  }
})

